<template>
  <div class="form-container">
    <el-form inline :model="form" ref="ruleForm" class="form-line" label-width="70">
      <el-form-item label="公司名称" prop="companyName">
        <el-input size="default" v-model="form.companyName" placeholder="请输入公司名称"></el-input>
      </el-form-item>
      <el-form-item label="所属城市" prop="city">
        <el-select size="default" v-model="form.city" placeholder="请选择城市">
          <el-option v-for="item in cityOptions" :key="item.cityId" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="btn-container">
      <el-button type="primary" @click="handleReset(ruleForm as FormInstance)">重置</el-button>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="primary" @click="handleAdd">添加</el-button>
    </div>
  </div>
  <div class="table-container">
    <el-table
      border
      :cell-style="{ textAlign: 'center', fontSize: '13px' }"
      :header-cell-style="{
        textAlign: 'center',
        fontWeight: '100',
        fontSize: '13px',
        color: 'white',
        backgroundColor: '#009688'
      }"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column fixed prop="companyName" label="公司名称" />
      <el-table-column prop="city" label="所属城市">
        <template #default="scope">{{ cityOptions.find(item => item.code === scope.row.city)?.name }}</template>
      </el-table-column>
      <el-table-column prop="adminUsername" label="账号" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleDelete(scope.row.companyId)">删除</el-button>
          <el-button link type="primary" size="small" @click="handleEdit(scope.row.companyId)"> 修改 </el-button>
          <el-button link type="primary" size="small" @click="handleResetPwd(scope.row.companyId)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        size="small"
        v-model:current-page="form.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        layout="prev, pager, next"
        :total="pageTotal"
        :page-size="form.pageSize"
        @change="getCompanyList"
      />
    </div>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getCompanyListAPI, restPwdAPI, CompanyDeleteAPI } from "@/api/modules/province/organizMangeAPI";
import { Company } from "@/api/interface/province/organizationManage";
import { Dict } from "@/api/interface/dict";
import { getCityListDictAPI } from "@/api/modules/dictAPI";
const router = useRouter();
//ProCompanyType 已经通过declare全局申明过不用再单独导入
let tableData = ref<Company.CompanyList[]>([]);
const pageTotal = ref<number>(0);
const form = ref<Company.CompanySearchForm>({
  companyName: "",
  city: "",
  pageNum: 1,
  pageSize: 10,
  userId: 1
});
const ruleForm = ref<FormInstance>();
const handleEdit = (id: number) => {
  router.push({
    path: "/provinceLevel/proOrganization/proCompany/add",
    query: { id: id }
  });
};
const handleReset = (Elform: FormInstance) => {
  Elform.resetFields();
};

const handleSearch = (): void => {
  getCompanyList();
  console.log("查询", form.value);
};
const handleAdd = (): void => {
  router.push("/provinceLevel/proOrganization/proCompany/add");
};
const handleDelete = (id: number): void => {
  ElMessageBox.confirm(`确定删除该条记录${name}吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteCompany(id);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除"
      });
    });
};
const handleResetPwd = (id: number): void => {
  ElMessageBox.confirm(`确定重置该条记录${name}的密码吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      restPwd(id);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消重置密码"
      });
    });
};
// 重置密码
const restPwd = async (id: number) => {
  const { code, msg } = await restPwdAPI({ companyId: id });
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "重置密码成功!"
    });
  } else {
    ElMessage.error(`重置密码失败,${msg}`);
  }
};
// 删除公司
const deleteCompany = async (id: number) => {
  const { code, msg } = await CompanyDeleteAPI(id);
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "删除成功!"
    });
    getCompanyList();
  } else {
    ElMessage.error(`删除失败,${msg}`);
  }
};
// 列表接口请求地址
const getCompanyList = async () => {
  const { rows, code, msg, total } = await getCompanyListAPI(form.value);
  if (code == "200" && rows && total) {
    tableData.value = rows;
    pageTotal.value = total;
    console.log("公司列表", tableData);
  } else {
    ElMessage.error(msg);
  }
};
const cityOptions = ref<Dict.CityListData[]>([]);
const getCityListDict = async () => {
  const { data, code } = await getCityListDictAPI({
    parentCode: JSON.parse(localStorage.getItem("userInfo") as string).province
  });
  if (code == "200" && data) {
    cityOptions.value = data;
  } else {
    ElMessage.error("获取城市列表失败");
  }
};
onMounted(() => {
  console.log(JSON.parse(localStorage.getItem("userInfo") as string));
  form.value.userId = JSON.parse(localStorage.getItem("userInfo") as string).userId;
  getCompanyList();
  getCityListDict();
});
</script>
<style lang="scss" scoped>
.form-container {
  padding: 10px;
  margin-bottom: 10px;
  background-color: white;
  .btn-container {
    display: inline-block;
    float: right;
    vertical-align: middle;
    ::v-deep .el-button > span {
      font-size: 13px;
    }
  }
  .el-form {
    display: inline-block;
    ::v-deep .el-form-item__label {
      font-size: 13px;
    }
  }
  .form-line {
    .el-form-item {
      margin: 0;
      margin-right: 20px;
    }
    .el-input {
      width: 240px;
    }
    .el-select {
      width: 240px;
    }
  }
}
.table-container {
  padding: 40px 10px;
  padding-bottom: 60px;
  background-color: white;
  .pagination-container {
    // display: inline-block;
    float: right;
    margin-top: 20px;
    background-color: white;
  }
}
</style>
